<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/static/2d.css">
    <title>Document</title>

</head>
<body>
    <div id="app">
        <div class="header">
        </div>
        <div class="menu">
            <h2>人物动作选择</h2>
                <div class="menu-item">

                    <ul>
                        <li>
                            <a href="">
                                <!-- <img src="https://pic.616pic.com/ys_bnew_img/00/12/60/S7UzksqXB0.jpg" alt=""> -->
                                 <video preload="/static/video/zou1.mp4#t=1" src="/static/video/zou1.mp4"></video>
                            </a>
                        </li>
                        <li class="active">
                            <a href="" >
                                <!-- <img src="https://pic.616pic.com/ys_bnew_img/00/12/60/S7UzksqXB0.jpg" alt=""> -->
                                <video preload="/static/video/qiu1.mp4#t=1" src="/static/video/qiu1.mp4"></video>
                            </a>
                        </li>
                        <li class="active">
                            <a href="" >
                                <!-- <img src="https://pic.616pic.com/ys_bnew_img/00/12/60/S7UzksqXB0.jpg" alt=""> -->
                                <video preload="/static/video/chen1.mp4#t=2" src="/static/video/chen1.mp4"></video>
                            </a>
                        </li>
                    </ul>
                    <div>
                        <input type="file" id="audioFile1" accept=".mp4" />
                        <button onclick="uploadFile2()" style="
                          cursor: pointer;
                        "><img src="{{ url_for('static', filename='images/video.png') }}" alt="图片5"><span>上传文件</span></button>
                        <div>
                            <label for="taskCodeBox22" style="display: none;">视频文件名：</label>
                            <input type="text" id="taskCodeBox22" style="display: none;" readonly style="width: 300px; " />
                          </div>
                      </div>
                </div>
                <h2>声音克隆设置</h2>
                <div class="menu-item1">

                    <input type="file" id="audioFile" label="选择音频文件" accept=".wav">

                    <button onclick="uploadFile()" style="cursor: pointer;">
                        <img src="{{ url_for('static', filename='images/video.png') }}" alt="图片5">
                        <span>开始克隆</span>
                    </button>
                    <div>
                    <label for="taskCodeBox11" style="display: none;">音频文件名：</label>
                    <input type="text" id="taskCodeBox11" readonly style="width: 200px;display: none;">
                    </div>
                </div>
                <h2>PPT模板选择</h2>
                <div class="menu-item2">

                    <ul>

                        <li> <img src="{{ url_for('static', filename='images/ppt/1.png') }}" alt="图片1"></li>
                        <li> <img src="{{ url_for('static', filename='images/ppt/2.png') }}" alt="图片2"></li>
                        <li> <img src="{{ url_for('static', filename='images/ppt/3.png') }}" alt="图片3"></li>
                        <li> <img src="{{ url_for('static', filename='images/ppt/4.png') }}" alt="图片4"></li>
                    </ul>
                    <a href="">更多模板</a>
                    <br>
                    <button><img src="{{ url_for('static', filename='images/video.png') }}" alt="图片5"><span>上传自定义模板</span></button>
                </div>
            </div>



          <div class="PPT">
            <h2>ppt内容预览</h2>
            <div class="PPT-item">
                <!-- <span><img src="https://pic.616pic.com/ys_bnew_img/00/12/60/S7UzksqXB0.jpg" alt=""></span>   -->
                <video  id="vid" width="1040" height="585" controls="controls" ><source type="video/mp4"></video>


            </div>
            <div class="PPT-img">
                <ul>
                    <li><img src="" alt=""></li>
                    <li><img src="{{ url_for('static', filename='images/ppt/10.png') }}" alt="图片6"></li>
                    <li><img src="{{ url_for('static', filename='images/ppt/11.png') }}" alt="图片7"></li>
                    <li><img src="{{ url_for('static', filename='images/ppt/12.png') }}" alt="图片8"></li>
                    <li><img src="{{ url_for('static', filename='images/ppt/13.png') }}" alt="图片9"></li>
                    <li><img src="" alt=""></li>
                </ul>
            </div>
            <div class="PPT-write" style="margin-top: 20px;">
                <label for="taskCodeInput" style="display: none;">查询进度（输入任务码）:</label>
                <input type="text" id="taskCodeInput" placeholder="请输入任务码"  style="display: none;"/>
                <div>
                <button onclick="queryProgressFromInput()" style="width: 80px;height:40px; font-size: 15px;">查询进度</button>
                <button onclick="startVideoMerge()"style="width: 80px;height:40px; font-size: 15px;">开始合成</button>
                </div>
                <hr>
                <label for="taskCodeBox" style="display: none;">任务编号：</label>
                <input type="text" id="taskCodeBox" readonly style="display:none;">

                  <label for="taskCodeBox" style="display: none;">结果位置(调试使用)：</label>
                <input type="text" id="taskcom" readonly style="display: none;">

                <div id="log" style="width: 1045px;height: 150px;border: #2c3e50 2px solid;background-color:rgb(255, 255, 255);"></div>
            </div>
        </div>

    </div>







    <h2>视频上传</h2>
<div class="video-upload">
    <!-- PPT视频上传 -->
    <div class="upload-group">
        <label>PPT视频:</label>
        <input type="file" id="pptVideoFile" accept=".mp4" />
        <div class="file-info">
            <span>未选择文件</span>
            <progress id="pptVideoProgress" value="0" max="100"></progress>
        </div>
    </div>

    <!-- 微课程视频上传 -->
    <div class="upload-group">
        <label>微课程视频:</label>
        <input type="file" id="courseVideoFile" accept=".mp4" />
        <div class="file-info">
            <span>未选择文件</span>
            <progress id="courseVideoProgress" value="0" max="100"></progress>
        </div>
    </div>

    <!-- 背景选择 -->
    <div class="background-selection">
        <label>选择背景:</label>
        <div class="bg-options">
            <label><input type="radio" name="bgOption" value="bg1.png" checked> 背景1</label>
            <label><input type="radio" name="bgOption" value="bg2.png"> 背景2</label>
            <label><input type="radio" name="bgOption" value="bg3.png"> 背景3</label>
        </div>
    </div>

    <!-- 合成按钮 -->
    <button id="generateVideoBtn" onclick="generateSyntheticVideo()">生成合成视频</button>

    <!-- 结果区域 -->
    <div id="resultSection" style="display:none; margin-top:20px;">
        <video id="resultVideo" width="400" controls></video>
        <a id="downloadLink" download="合成视频.mp4">下载视频</a>
    </div>
</div>
</body>
</html>

<!--<script src="{{ url_for('static', filename='js/script.js') }}"></script>-->
  <script>
  function logMessage(message) {
      const log = document.getElementById('log');
      log.textContent += message + '\n';
      log.scrollTop = log.scrollHeight;
    }

    async function submitVideoMerge() {
      const taskCode = crypto.randomUUID();
      /*console.log(taskCode)*/
      const audioUrl = document.getElementById('taskCodeBox11').value;
      const videoUrl = document.getElementById('taskCodeBox22').value;


      const payload = {
        audio_url: audioUrl,
        video_url: videoUrl,
        code: taskCode,
        chaofen: 0,
        watermark_switch: 0,
        pn: 1
      };
      try {
        const response = await fetch('http://127.0.0.1:5000/api/submit', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)}
        );
        if (!response.ok) {
          throw new Error(`提交失败：${response.status}`);
        }
        const data = await response.json();

        console.log(data.success);

        if (data.success) {
          /*返回任务编号到上*/
          document.getElementById("taskCodeBox").value = taskCode;
          document.getElementById("taskCodeInput").value = taskCode;
          console.log("生成的任务编号：", taskCode);
          logMessage(`✅ 合成任务已提交，任务码：${taskCode}，`);
          return taskCode;

        } else {
          logMessage(`❌ 合成失败，消息：${data.msg}`);
          return null;
        }
      } catch (error) {

        logMessage(`❌ 失败了：${error}`);

        return null;
      }
    }
    async function startVideoMerge() {
      const audioUrl = document.getElementById('taskCodeBox11').value.trim();
      const videoUrl = document.getElementById('taskCodeBox22').value.trim();
      if (!audioUrl || !videoUrl) {
        alert('请输入音频和视频的完整地址！');
        return;
      }
      const taskCode = await submitVideoMerge(audioUrl, videoUrl);
      if (taskCode) {
        // 提交成功后，自动调用查询进度
        await queryProgressFromCode(taskCode);
      }

    }
    async function queryProgressFromInput() {
      const code = document.getElementById('taskCodeInput').value.trim();
      if (!code) {
        alert('请输入任务码');
        return;
      }
      await queryProgressFromCode(code);
    }


    async function queryProgressFromCode(taskCode) {
      logMessage(`🔄 开始查询任务码：${taskCode} 的合成进度...`);

      try {
        const response = await fetch(`http://localhost:5000/api/query?code=${taskCode}`);
        if (!response.ok) {
          throw new Error(`查询失败，状态码：${response.status}`);
        }
        const data = await response.json();


        if (data.code == 10004){
          logMessage(`📊 查询结果：1.任务早已完成  2.任务不存在  3.服务器还没初始化,等待后重试`);
        }else {
          logMessage(`📊 查询结果：任务进行中`);
          logMessage(`📊 目前情况：${data.data.msg}`);
          logMessage(`📊结果路径：${data.data.result}`);
          //这个是把结果显示到界面上
          document.getElementById("taskcom").value = `${data.data.result}`;
          //这个是把视屏显示大页面上
          const videoPath= data.data.result;  // e.g. "/xxx.mp4"
          document.getElementById('vid').querySelector('source').src = `http://localhost:5000/download${videoPath}`;
          document.getElementById('vid').load();
        }

        logMessage(`📊 状态码：${data.code}`);
      } catch (error) {
        logMessage(`⚠️ 查询出错：${error}`);
      }
    }

  //下载视频
    function downloadResult() {
      //const filePath = data.data.result;  // 例如 "/abc-123-r.mp4"
      //console.log(filePath)
      const input = document.getElementById('taskcom').value;  // e.g. "/abc-123-r.mp4"
      console.log(input)

      const fileName = input.split('/').pop();  // 得到 "abc-123-r.mp4"
      const downloadUrl = `http://localhost:5000/download/${encodeURIComponent(fileName)}`;
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = fileName;  // 建议加上，确保浏览器弹出保存
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }


    //上传文件
  async function uploadFile() {
  const fileInput = document.getElementById("audioFile");
  const fileNameDisplay = document.getElementById("fileName");

  if (!fileInput.files.length) {
    alert("请选择一个 WAV 文件！");
    return;
  }
  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append("file", file);

  try {
    const response = await fetch("http://127.0.0.1:5000/api/uploads2", {
      method: "POST",
      body: formData
    });
    if (!response.ok) {
      const text = await response.text();
      alert("上传失败：" + text);
      return;
    }
    const data = await response.json();
    alert("上传成功！文件路径：" + data.file_path);
  // 显示后端返回的文件名到只读输入框
    taskCodeBox11.value = data.file_path;

  } catch (err) {
    alert("上传请求出错：" + err.message);
  }
}

  async function uploadFile2() {
    const fileInput = document.getElementById('audioFile1');
    const file = fileInput.files[0];
    const filenameInput = document.getElementById('taskCodeBox22');

    if (!file) {
      alert('请先选择一个 MP4 文件');
      return;
    }
    if (!file.name.endsWith('.mp4')) {
      alert('请选择一个 .mp4 格式的视频文件');
      return;
    }
    // 构造 FormData 上传文件
    const formData = new FormData();
    formData.append('file', file);
    try {
      const response = await fetch('http://127.0.0.1:5000/api/uploads2', {
        method: 'POST',
        body: formData
      });
      if (!response.ok) {
        throw new Error(`上传失败: ${response.status}`);
      }
      // 假设接口返回 JSON { filename: "上传后文件名.mp4", ... }
      const data = await response.json();
      // 把文件名显示到 readonly 输入框
      filenameInput.value = data.filename || file.name;
      alert('文件上传成功！');
    } catch (error) {
      console.error('上传失败:', error);
      alert('上传失败：' + error.message);
    }
  }













  // 全局变量存储上传后的视频信息
let uploadedFiles = {
    pptVideo: null,
    courseVideo: null
};

// 上传PPT视频
document.getElementById('pptVideoFile').addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const file = this.files[0];
        uploadVideo(file, 'pptVideo');
    }
});

// 上传微课程视频
document.getElementById('courseVideoFile').addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const file = this.files[0];
        uploadVideo(file, 'courseVideo');
    }
});

// 通用的视频上传函数
async function uploadVideo(file, type) {
    const progressBar = document.getElementById(`${type}Progress`);
    const fileInfoSpan = progressBar.parentNode.querySelector('span');

    // 更新UI
    fileInfoSpan.textContent = `上传中: ${file.name} (0%)`;
    progressBar.value = 0;

    try {
        const formData = new FormData();
        formData.append('file', file);

        const response = await fetch('http://127.0.0.1:5000/api/uploads2', {
            method: 'POST',
            body: formData,
            onUploadProgress: (event) => {
                const percent = Math.round((event.loaded * 100) / event.total);
                progressBar.value = percent;
                fileInfoSpan.textContent = `上传中: ${file.name} (${percent}%)`;
            }
        });

        if (!response.ok) {
            throw new Error(`上传失败: ${response.status}`);
        }

        const data = await response.json();
        fileInfoSpan.textContent = `上传成功!`;

        // 保存上传后的文件信息
        uploadedFiles[type] = {
            path: data.file_path,
            name: file.name
        };

    } catch (error) {
        console.error('上传失败:', error);
        fileInfoSpan.textContent = `上传失败: ${error.message}`;
        progressBar.value = 0;
    }
}

// 生成合成视频
async function generateSyntheticVideo() {
    // 检查是否已上传两个视频
    if (!uploadedFiles.pptVideo || !uploadedFiles.courseVideo) {
        alert('请先上传PPT视频和微课程视频');
        return;
    }

    const generateBtn = document.getElementById('generateVideoBtn');
    const originalText = generateBtn.textContent;
    generateBtn.textContent = '合成中...';
    generateBtn.disabled = true;

    try {
        // 获取选中的背景
        const bgOption = document.querySelector('input[name="bgOption"]:checked').value;

        // 调用后端API
        const response = await fetch('http://localhost:5000/api/generate_composite_video', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        background: "static\backgrounds\default.png",
        video1: "uploaded_ppt.mp4",
        video2: "uploaded_course.mp4",
        pos1: [146, 242],
        size1: [975, 550],
        pos2: [1000, 100],
        size2: [1400, 1050]
    })
});


        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `合成失败: ${response.status}`);
        }

        const result = await response.json();
        const videoPlayer = document.getElementById('resultVideo');
        videoPlayer.src = result.download_url;
        // 更新UI显示合成视频
        document.getElementById('resultSection').style.display = 'block';
        const resultVideo = document.getElementById('resultVideo');
        resultVideo.src = result.download_url;

        // 设置下载链接
        const downloadLink = document.getElementById('downloadLink');
        downloadLink.href = result.download_url;
        downloadLink.textContent = `下载: ${result.filename}`;
        downloadLink.download = result.filename;

    } catch (error) {
        console.error('合成失败:', error);
        alert(`合成失败: ${error.message}`);
    } finally {
        generateBtn.textContent = originalText;
        generateBtn.disabled = false;
    }
}
async function generateCompositeVideo() {
    try {
        const payload = {
            video1: "path/to/ppt-video.mp4",
            video2: "path/to/course-video.mp4",
            pos1: [146, 242],
            size1: [975, 550],
            pos2: [1300, 100],
            size2: [610, 1050]
        };

        const response = await fetch('/api/generate_composite_video', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        });

        // 处理响应...
    } catch (error) {
        // 错误处理...
    }
}
  </script>
</body>
</html>